<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\HoneyBalance;
use App\Models\User;
use App\Services\HoneyBalanceService;
use Dingo\Api\Http\Request;

class UserController extends BaseController
{

    public $model = User::class;
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $model = new $this->model;
        $nickname = $request->input('nickname');
        $mobile = $request->input('mobile');
        $audit_status = $request->input('audit_status', -1);
        $city = $request->input('city');
        $start_at = $request->input('start_at');
        $end_at = $request->input('end_at');
        $is_admin = $request->input('is_admin', -1);
        $order_by_key = $request->input('order_by_key', 'id');
        $order_by_value = $request->input('order_by_value', 'desc');

        $users = $model->nickName($nickname)
            ->mobile($mobile)
            ->when($is_admin != -1, function ($q) use($is_admin){
                $q->where('is_admin', $is_admin);
            })
            ->auditStatus($audit_status)
            ->city($city)
            ->startAt($start_at)
            ->endAt($end_at)
            ->orderBy("$order_by_key", "$order_by_value")
            ->paginate(\request('per_page', 20));

        return $this->paginate($users);
    }

    public function editStatus(Request $request) {
        $this->validate($request, [
            'ids' => 'required',
            'value' => 'required',
            'action' => 'required'
        ]);
        $value = \request('value');
        $action = \request('action');
        $ids = $request->input('ids');
        $reason = \request('reason');
        $arr_id = explode(",", $ids);

        $list = $this->model::whereIn('id', $arr_id)->get();
        \DB::transaction(function () use($list, $action, $value, $reason){
            $old_status = 0;
            foreach ($list as $item) {
                if ($action == 'audit') {
                    $item->audit_status = $value;
                    $item->reason = $reason;
                } elseif ($action == 'black') {
                    $item->is_black = $value;
                } else if($action == 'admin') {
                    $item->is_admin = $value;
                }
                if ($item->save()) {
                    if ($action == 'audit') {
                        if ($value == 3) {
                            $exists = HoneyBalance::where('entity_id', $item->id)->where('type', HoneyBalance::POINT_IDENTIFY)->where('user_id', $item->user_id)->exists();
                            if (!$exists)
                                HoneyBalanceService::store($item->id, HoneyBalance::POINT_IDENTIFY, HoneyBalance::POINT_IDENTIFY, $item->id, false);
                        }
                    }
                }
            }
        });

        return $this->success([]);
    }

}

